﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using webapi.DTO;
using webapi.Helper;

namespace webapi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class AuthController : ControllerBase
    {
        IConfiguration _configuration;
        public AuthController(IConfiguration configuration)
        {
            _configuration = configuration;
        }



        /// <summary>
        /// 获取token
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public IActionResult gettoken()
        {
            var token = new JwtHelper(_configuration).GenerateJwtToken(new Model.UserJwt() { UserEmail = "726557953@qq.com", UserGroupId = "0" });
            return Content(token);
        }


        /// <summary>
        /// 测试token
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public IActionResult test()
        {
            var user = HttpContext.User.Claims;
            // 获取Email
            var userEmail = user.FirstOrDefault(c => c.Type == "UserEmail")?.Value;
            // 获取用户组
            var userGroup = user.FirstOrDefault(c => c.Type == "UserGroupId")?.Value;
            return Content("请求成功");
        }

        //[HttpGet]
        //[Route("/GetToken")]
        //public ActionResult<string> GetToken(AuthInputDTO input)
        //{
        //    //这里我写死了，后边可以写一个实体，输入用户名和密码放进这里
        //    var claims = new[]
        //   {
        //        new Claim(ClaimTypes.Name, input.email),
        //        new Claim(ClaimTypes.Upn, input.password)
        //    };
        //    //发行者

        //    var isyouruser = _config.GetValue<string>("JWT:ISyouuser");
        //    //接受者

        //    var isAudience = _config.GetValue<string>("JWT:IsAudience");
        //    //秘钥key

        //    var scKey = _config.GetValue<string>("JWT:SignKey");
        //    //设置token的过期时间

        //    DateTime timeout = DateTime.Now.AddMinutes(30);
        //    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(scKey));
        //    var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);


        //    var jwtToken = new JwtSecurityToken(isyouruser, isAudience, claims, expires: timeout, signingCredentials: credentials);

        //    // TODO: 认证错误，待修改
        //    var token = new JwtSecurityTokenHandler().WriteToken(jwtToken);

        //    return "Bearer " + token;
        //}
    }
}
